<?php

namespace App\Admin\Renderable;

use App\Models\Administrator;
use App\Models\XXlBaseForm;
use Carbon\Carbon;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class DispatchUser extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * 处理请求
     * 获取 重新分配表单的ID
     * 如果表单已分配, 并且分配时间为当天, 把之前分配人员的当天分配数 - 1
     * 如果不是当天分配的,不处理之前分配人员的当天分配数
     *
     * @param array $input
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        // id转化为数组
        $id = data_get($this->payload, 'id') ?? explode(',', $input['id'] ?? null);
        if (!$id) return $this->response()->error('参数错误');

        $userId = $input['user_id'];
        if (!$userId || !$user = Administrator::find($userId))
            return $this->response()->error('分配给错误的用户!');

        $form = XXlBaseForm::query()
            ->with([
                'user' => function ($q) {
                    $q->select([
                        'id'
                    ]);
                }
            ])
            ->select([
                'id',
                'dispatch_date',
            ])
            ->whereIn('id', (array)$id)
            ->get();

        $date = Carbon::today()->toDateString();

        $form->each(function ($item) use ($date, $user) {
            $user->userGetOne("$date.{$user->id}");
            if ($item->user &&
                $item['dispatch_date'] &&
                Carbon::parse($item['dispatch_date'])->isToday()
            ) {
                $preUser = $item->user->first();
//                dd($preUser,data_get($item , 'user.0.id'));
                $preUser->userForgetOne("$date.{$preUser->id}");
            }
        });
        XXlBaseForm::setDispatchDate($id, Carbon::now());

        DB::table('admin_user_has_test_form')
            ->whereIn('form_id', (array)$id)
            ->delete();

        $user->baseForm()->attach($id);

        return $this->response()->success('分配成功')->refresh();
    }

    public function form()
    {

//        $items = Administrator::getDispatchUserList();
        $this->selectTable('user_id', '分配用户')
            ->title('咨询列表')
            ->dialogWidth('50%') // 弹窗宽度，默认 800px
            ->from(DispatchUserTable::make()->payload([
                'group_id' => data_get($this->payload, 'group_id')
            ])) // 设置渲染类实例，并传递自定义参数
            ->model(Administrator::class, 'id', 'name');


        $this->hidden('id')->attribute('id', 'order-status-id');
    }

    public function default()
    {
        return [
            'user_id' => data_get($this->payload, 'user_id')
        ];
    }
}
